import json

# Create your views here.
import os
import dbm

from django.http import HttpResponse, JsonResponse

MAX_SIZE = 10

FILE_NAME = "kvdb"
RTMPS_KEY = "rmtps"


def response_success(request, data=None):
    if data:
        return {"code": 200, "ip": get_client_ip(request), "msg": "success", "data": data}
    else:
        return {"code": 200, "ip": get_client_ip(request), "msg": "success"}


def response_error(request, code: int, msg: str):
    return {"code": code, "ip": get_client_ip(request), "msg": msg}


def rmtp_api(request):
    print(request)
    if request.method == "POST":
        return add_rtmp(request)

    if request.method == "GET":
        return get_rtmp(request)

    return response_error(request, 10000, f"un_support {request.method}")


def get_rtmp(request):
    print(request.GET)
    size = int(request.GET.get('size', default='0'))
    rtmps = get_all_rtmps()
    if size == 0 or len(rtmps) <= size:
        data = rtmps
    else:
        data = rtmps[0:size]
    return JsonResponse(response_success(request, data))


def add_rtmp(request):
    req = json.loads(request.body)
    print(req)
    url = req['url']
    add_url(url)
    return JsonResponse(response_success(request))


def add_url(url: str):
    rtmps = get_all_rtmps()
    rtmps.insert(0, url)
    while len(rtmps) > MAX_SIZE:
        rtmps.pop(MAX_SIZE)
    db = dbm.open(FILE_NAME, 'c')
    db[RTMPS_KEY] = json.dumps(rtmps)


def get_all_rtmps():
    db = dbm.open(FILE_NAME, 'c')

    if RTMPS_KEY.encode(encoding='utf-8') in db.keys():
        return json.loads(db[RTMPS_KEY])
    return []


def get_client_ip(request):
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip
